package com.mingmen.canting.jingli;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.canting.R;
import com.mingmen.canting.activity.FilterKuaijieActivity;
import com.mingmen.canting.adapter.JingLiRuKuAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.chushizhang.JingLiCompareActivity;
import com.mingmen.canting.defineview.ClearEditText;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.JingLiRukuModel;
import com.mingmen.canting.model.ShujuModel;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.ScalableCardHelper;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

public class GongZhexianFragment extends Fragment implements ScalableCardHelper.OnPageChangeListener {

    @BindView(R.id.text_count)
    TextView textCount;
    Unbinder unbinder;
    @BindView(R.id.main_search)
    ClearEditText mainSearch;
    @BindView(R.id.layout_search)
    LinearLayout layoutSearch;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;
    @BindView(R.id.rv_photo_list)
    RecyclerView rvPhotoList;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    private String mTitle;
    List<String> mylist = new ArrayList<>();
    String token;

    List<JingLiRukuModel.DataBean> dataBeanList = new ArrayList<>();
    JingLiRuKuAdapter jingLiRuKuAdapter;
    //    List<JingLiRukuModel.DataBean.DetailsBean> detailsBeanList = new ArrayList<>();
    @BindView(R.id.text_compare)
    TextView text_compare;

    List<ShujuModel.DataBean> compareDataBeanList = new ArrayList<>();
    private int resurtResurant = 100;
    private int kuaijie = 100;
    String string = "{\"code\":0,\"message\":\"操作成功\",\"time\":\"2020-08-07 16:05:32\",\"data\":[{\"priceDate\":\"2020-08-01\",\"price\":200.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-02\",\"price\":210.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-03\",\"price\":250.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-04\",\"price\":180.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-05\",\"price\":300.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-06\",\"price\":200.00,\"maxPrice\":300.00,\"minPrice\":180.00}]}";

    @BindView(R.id.layout_calendafirst)
    LinearLayout layout_calendafirst;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;
    @BindView(R.id.layout_lineChart)
    LinearLayout layout_lineChart;
    TimePickerView pvTime;
    String startTime = "";
    String endTime = "";

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jingliruku, null);
        unbinder = ButterKnife.bind(this, view);
        TextView card_title_tv = (TextView) view.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        for (int i = 0; i < 10; i++) {
            mylist.add("ITem" + i);
        }
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_photo_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
//        recyclerView.setAdapter(new JingLiRuKuAdapter(getActivity(), dataBeanList));
        jingLiRuKuAdapter = new JingLiRuKuAdapter(getActivity(), dataBeanList);
        recyclerView.setAdapter(jingLiRuKuAdapter);
        ScalableCardHelper cardHelper = new ScalableCardHelper(this);
        cardHelper.attachToRecyclerView(recyclerView);
        getCaneda();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;
        textview_calendafirst.setText(data);
        textview_calendasecond.setText(data);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                pageNumber = 1;
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
//                getCateList(token, "", "", pageNumber);
                getData(token, "9", startTime, endTime, pageNumber, "");
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;
                    getData(token, "9", startTime, endTime, pageNumber, "");

                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });


        mainSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                Intent intent = new Intent(getActivity(), JingLiCompareActivity.class);
                intent.putExtra("logindata", s);
//                startActivityForResult(intent, resurtResurant);
            }
        });



        return view;
    }

    public void getData(String token, String st, String startTime, String endTime, int pageNumber, String commodityId) {
        HttpResponse.getConsumeBillList(token, st, startTime, endTime, pageNumber, commodityId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("JingLiRukuFragment", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    JingLiRukuModel jingLiRukuModel = new JingLiRukuModel();
                    jingLiRukuModel = GsonUtil.GsonToBean(s, JingLiRukuModel.class);
                    dataBeanList.addAll(jingLiRukuModel.getData());

                    jingLiRuKuAdapter.setDataList(dataBeanList);
                    textCount.setText(jingLiRukuModel.getData().size() + "");
                    totalPage = jingLiRukuModel.getTotalPage();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }
            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }


    public static GongZhexianFragment getInstance(String title) {
        GongZhexianFragment sf = new GongZhexianFragment();
        sf.mTitle = title;
        return sf;
    }

    int mypositon = 0;

    @Override
    public void onPageSelected(int position) {
        mypositon = position;
        Log.d("kdkkckkc", mypositon + "");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.main_search, R.id.layout_search, R.id.text_compare, R.id.layout_calendafirst, R.id.layout_calenda_second, R.id.layout_dingdan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_search:
                Intent intent = new Intent(getActivity(), JingLiCompareActivity.class);

                startActivityForResult(intent, resurtResurant);
                break;
            case R.id.layout_search:
                break;
            case R.id.text_compare:
                Log.d("TextCompare", compareDataBeanList.size() + "");

                if (TextUtils.isEmpty(commodityId)) {
                    Toast.makeText(getActivity(), "请选择商品", Toast.LENGTH_SHORT).show();
                } else {
                    HttpResponse.getComparePrice(token, startTime, endTime, commodityId, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("CompareCompare", s);
                            if (!compareDataBeanList.isEmpty()) {
                                compareDataBeanList.clear();
                            }
                            ShujuModel shujuModel = new ShujuModel();
                            shujuModel = GsonUtil.GsonToBean(s, ShujuModel.class);

                            compareDataBeanList = shujuModel.getData();

                            if (compareDataBeanList.size() == 0) {
                                layout_lineChart.setVisibility(View.GONE);
                                Toast.makeText(getActivity(), "当前无比价信息", Toast.LENGTH_SHORT).show();
                                rvPhotoList.setVisibility(View.VISIBLE);
                            } else {
                                rvPhotoList.setVisibility(View.GONE);
                                layout_lineChart.setVisibility(View.VISIBLE);


                            }

                        }
                    });
                }


                break;
            case R.id.layout_calendafirst:
                pvTime.show(layout_calendafirst);
                break;
            case R.id.layout_calenda_second:
                pvTime.show(layout_calenda_second);
                break;
            case R.id.layout_dingdan:
//                startActivity(new Intent(getActivity(), FilterKuaijieActivity.class));

                rvPhotoList.setVisibility(View.VISIBLE);
                layout_lineChart.setVisibility(View.GONE);

                intent = new Intent(getActivity(), FilterKuaijieActivity.class);

                intent.putExtra("count", textCount.getText().toString());
                intent.putExtra("kuaijie", "10");
                startActivityForResult(intent, kuaijie);
                break;
        }
    }


    String commodityId;
    String commodityName;
    String receiveposition;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
//            Toast.makeText(getActivity(), resultCode+"", Toast.LENGTH_SHORT).show();
            receiveposition = data.getStringExtra("jingliruku");
            int mysmooth = Integer.valueOf(receiveposition);
            rvPhotoList.scrollToPosition(mysmooth);
        } else if (resultCode == 100) {
            try {
                commodityId = data.getStringExtra("commodityId");
                commodityName = data.getStringExtra("commodityName");
                mainSearch.setText(commodityName);
                Log.d("ckkckc", commodityId + commodityName);
            } catch (Exception e) {

            }
        }


    }


    public void getCaneda() {


        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                Toast.makeText(getActivity(), getTime(date), Toast.LENGTH_SHORT).show();
                switch (v.getId()) {
                    case R.id.layout_calendafirst:
                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);

                        break;
                    case R.id.layout_calenda_second:
                        textview_calendasecond.setText(getTime(date));
                        endTime = getTime(date);

                        break;
                }


            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });


                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
